package com.yugao.fintech.framework.assistant.sign.core;

import com.yugao.fintech.framework.assistant.sign.SignException;
import com.yugao.fintech.framework.assistant.sign.SignType;
import org.reflections.Reflections;
import org.reflections.scanners.Scanners;
import org.reflections.util.ClasspathHelper;
import org.reflections.util.ConfigurationBuilder;
import org.reflections.util.FilterBuilder;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * 签名算法
 */
public abstract class HashAlgoProcess implements SignAlgoProcess {

    private static final Map<SignType, HashAlgoProcess> hashAlgoProcessMap = new HashMap<>();

    static {
        Reflections reflection = new Reflections(new ConfigurationBuilder()
                .setScanners(Scanners.SubTypes)
                .setUrls(ClasspathHelper.forPackage(HashAlgoProcess.class.getPackage().getName()))
                .filterInputsBy(new FilterBuilder()));
        Set<Class<? extends HashAlgoProcess>> subTypesOf = reflection.getSubTypesOf(HashAlgoProcess.class);
        for (Class<? extends HashAlgoProcess> aClass : subTypesOf) {
            try {
                HashAlgoProcess hashAlgoProcess = aClass.newInstance();
                hashAlgoProcessMap.put(hashAlgoProcess.getSignTYpe(), hashAlgoProcess);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static HashAlgoProcess getAlgoProcess(SignType signType) {
        HashAlgoProcess hashAlgoProcess = hashAlgoProcessMap.get(signType);
        if (Objects.isNull(hashAlgoProcess)) {
            throw new SignException("未实现签名算法处理器, 请联系提供者");
        }
        return hashAlgoProcess;
    }

    public abstract String process(String req) throws Exception;
}
